/* 交通规律理解系统/道路交通基本信息展现 */
<template>
  <div class="subpage--main">
    <ACard class="section">
      <ARow :gutter="20">
        <ACol :span="10">
          <div class="form">
            <div class="form__title">道路路段</div>
            <div class="form__body">
              <div class="form__item">
                <div class="form__item__label">道路类型：</div>
                <div>
                  <ACheckboxGroup
                    :options="ROAD_TYPES"
                    v-model="road.types"
                    @change="handleChange('road')"
                  />
                </div>
              </div>
              <div class="form__item">
                <div class="form__item__label">通行状态：</div>
                <div>
                  <ACheckboxGroup
                    :options="ROAD_STATUS"
                    v-model="road.status"
                    @change="handleChange('road')"
                  />
                </div>
              </div>
              <div class="form__item">
                <div class="form__item__label">道路名称：</div>
                <div>
                  <AInput
                    v-model="road.name"
                    placeholder="支持模糊匹配"
                    @change="handleChange('road')"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="form">
            <div class="form__title">建筑规划</div>
            <div class="form__body">
              <div class="form__item">
                <div class="form__item__label">用地类型：</div>
                <div>
                  <ACheckboxGroup
                    :options="BUILDING_LAND_USE_TYPES"
                    v-model="building.landUseTypes"
                    @change="handleChange('building')"
                  />
                </div>
              </div>
              <div class="form__item">
                <div class="form__item__label">建筑类型：</div>
                <div>
                  <ACheckboxGroup
                    :options="BUILDING_TYPES"
                    v-model="building.buildingTypes"
                    @change="handleChange('building')"
                  />
                </div>
              </div>
              <div class="form__item">
                <div class="form__item__label">建筑名称：</div>
                <div>
                  <AInput
                    v-model="building.name"
                    placeholder="支持模糊匹配"
                    @change="handleChange('building')"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="form">
            <div class="form__title">交通设备</div>
            <div class="form__body">
              <div class="form__item">
                <div class="form__item__label">设备类型：</div>
                <div>
                  <ARadioGroup
                    :options="['卡口', '红绿灯']"
                    v-model="equipment.type"
                    @change="handleChange('equipment')"
                  />
                </div>
              </div>
              <div class="form__item">
                <div class="form__item__label">设备名称：</div>
                <div>
                  <AInput
                    v-model="equipment.name"
                    placeholder="支持模糊匹配"
                    @change="handleChange('equipment')"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="form">
            <div class="form__title">公共交通</div>
            <div class="form__body">
              <div class="form__item">
                <div class="form__item__label">公交类型：</div>
                <div>
                  <ARadioGroup
                    :options="['公交线路', '公交站点']"
                    v-model="massTransit.type"
                    @change="handleChange('massTransit')"
                  />
                </div>
              </div>
              <div class="form__item">
                <div class="form__item__label">线路/站点：</div>
                <div>
                  <AInput
                    v-model="massTransit.name"
                    placeholder="支持模糊匹配"
                    @change="handleChange('massTransit')"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="t-c">
            <AButton
              type="primary"
              size="large"
              @click="apply"
            >确认</AButton>
          </div>
        </ACol>
        <ACol :span="14">
          <div
            ref="map"
            class="map"
          ></div>
        </ACol>
      </ARow>
    </ACard>
    <ACard v-if="table">
      <ATable v-bind="table" />
    </ACard>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import { importVendor, drawPassports, drawTrafficSignals, drawBusStations, drawRoads, drawBuildings, drawBusRoutes } from '@/utils';
import { AMapScriptSrc } from '@/vendors';
import * as baseLayerAPI from '@/api/baseLayer';

type ColumnSource = [string, string, object?];
const roadColumens: ColumnSource[] = [
    // ['道路标识', 'roadId'],
    ['道路名称', 'roadName'],
    ['道路级别', 'roadLevel'],
    // ['道路起点', 'roadStartName'],
    // ['道路终点', 'roadEndName'],
    ['道路长度(km)', 'roadLong'],
    ['路段数量', 'partsCnt'],
    ['车道总数', 'laneCnt'],
    ['限速情况(km/h)', 'speedLimit'],
    ['红绿灯数量', 'trafficLightCnt'],
    ['道路交通卡口数量', 'checkPointCnt'],
    ['是否施工', 'isConstruction']
];
const buildingColumns: ColumnSource[] = [['用地类型', 'landType'], ['建筑类型', 'buildingType'], ['建筑名称', 'buildName'], ['地址', 'address'], ['相邻道路', 'roadName']];
const passportColumns: ColumnSource[] = [
    ['卡口名称', 'deviceName'],
    // ['采集方式', 'key'],
    // ['设备编号', 'key'],
    // ['设备地点', 'key'],
    // ['路段代码', 'key'],
    // ['地点代码', 'key'],
    // ['道路米数', 'key'],
    // ['道路方向', 'key'],
    ['卡口经度', 'lng'],
    ['卡口纬度', 'lat']
];
const trafficSignalColumns: ColumnSource[] = [
    ['红绿灯名称', 'deviceName'],
    // ['红绿灯地点', 'key'],
    // ['红绿灯对应路段', 'key'],
    // ['红绿灯配时', 'key'],
    ['红绿灯经度', 'lng'],
    ['红绿灯纬度', 'lat']
];
const busRouteColumns: ColumnSource[] = [
    // ['线路标识', 'lineId'],
    ['线路名称', 'lineName'],
    // ['线路起始站标识', 'startSiteId'],
    ['起点站名', 'startSiteName'],
    // ['线路终点站标识', 'endSiteId'],
    ['终点站名', 'endSiteName'],
    // ['有向线路方向', 'key'],
    ['首班时间', 'startLineTime'],
    ['末班时间', 'endLineTime'],
    ['是否主方向', 'isMainDirect'],
    ['是否区间车', 'isSection']
];
const busStationColumns: ColumnSource[] = [
    // ['站点标识', 'siteId'],
    ['站点名称', 'siteName'],
    ['站点经度', 'longitude'],
    ['站点纬度', 'latitude'],
    ['所属行政区域', 'areaName'],
    ['所属道路', 'roadName'],
    ['所属公共交通线路', 'lineList']
];

interface ITable {
    rowKey: string;
    columns: object[];
    dataSource: object[];
    [key: string]: any;
}

@Component({
    name: 'base-layer'
})
export default class Page extends Vue {
    ROAD_TYPES = ['主干道', '次干道', '支路', '其他'].map((label, i) => ({ label, value: i + 1 }));
    ROAD_STATUS = ['正常通行', '施工中', '已失效'].map((label, i) => ({ label, value: i + 1 }));
    road = {
        types: [],
        status: [],
        name: ''
    };
    BUILDING_LAND_USE_TYPES = ['农用地', '商业用地', '建设用地', '旅游用地', '居民住宅地', '其他'].map((label, i) => ({ label, value: i + 1 }));
    BUILDING_TYPES = ['学校', '医院', '商业中心', '住宅区', '其他'].map((label, i) => ({ label, value: i + 1 }));
    building = {
        landUseTypes: [],
        buildingTypes: [],
        name: ''
    };
    equipment = {
        type: '',
        name: ''
    };
    massTransit = {
        type: '',
        name: ''
    };
    selectedDimension: null | keyof Page = null;
    table: null | ITable = null;
    map: object = {};
    activeRowKey: string | null = null;

    mounted() {
        importVendor('AMap', AMapScriptSrc).then(() => {
            this.map = new AMap.Map(this.$refs.map as HTMLElement, {
                zoom: 13,
                center: [113.870836, 23.109164],
                showIndoorMap: false,
                features: ['bg', 'road', 'building']
            });
            this.$on('drawRoads', drawRoads);
            this.$on('drawBuildings', drawBuildings);
            this.$on('drawPassports', drawPassports);
            this.$on('drawTrafficSignals', drawTrafficSignals);
            this.$on('drawBusRoutes', drawBusRoutes);
            this.$on('drawBusStations', drawBusStations);
        });
    }

    handleChange(name: keyof Page) {
        // clear other dimensions
        const dimensions: Array<keyof Page> = ['road', 'building', 'equipment', 'massTransit'];
        dimensions
            .filter(item => item !== name)
            .forEach(name => {
                for (const key in this[name]) {
                    this[name][key] = key === 'name' || key === 'type' ? '' : [];
                }
            });
        this.selectedDimension = name;
    }
    async handleRoad() {
        const { types, status } = this.road;
        // if (!types.length || !status.length) {
        //     return this.$message.error('无效的条件');
        // }
        this.activeRowKey = null;
        this.table = {
            rowKey: 'roadId',
            columns: generateTableColumns(roadColumens),
            loading: true,
            dataSource: [],
            customRow: (row: any) => {
                return {
                    class: 'tr' + (this.activeRowKey === row.roadId ? ' tr--active' : ''),
                    on: {
                        click: () => {
                            this.activeRowKey = row.roadId;
                            this.$emit('drawRoads', this.map, row);
                        }
                    }
                };
            }
        };
        try {
            const data = await baseLayerAPI.listRoads({
                roadName: this.road.name,
                roadLevel: this.road.types,
                status: this.road.status
            });
            data.forEach((_: any) => (_.isConstruction = _.isConstruction === 1 ? '是' : '否'));
            this.table.dataSource = data;
        } finally {
            this.table.loading = false;
        }

        // 根据道路类型（主干道、次干道、城市支路）以不同颜色进行展现
        this.$emit('drawRoads', this.map, this.table.dataSource);

        // 点击“道路信息表格”中对应道路名称时，以特定的亮化颜色方式展现全程道路，
        // 并以图标的方式展现道路的起点、终点、道路中的红绿灯、道路中的卡口
    }
    async handleBuilding() {
        const { landUseTypes, buildingTypes } = this.building;
        // if (!landUseTypes.length || !buildingTypes.length) {
        //     return this.$message.error('无效的条件');
        // }
        this.activeRowKey = null;
        this.table = {
            rowKey: 'buildingId',
            columns: generateTableColumns(buildingColumns),
            loading: true,
            dataSource: [],
            customRow: (row: any) => {
              return {
                  class: 'tr' + (this.activeRowKey === row.buildingId ? ' tr--active' : ''),
                  on: {
                      click: async () => {
                          this.activeRowKey = row.buildingId;
                          let build = await baseLayerAPI.listBuildingRoads({
                              // @ts-ignore
                              buildingId: this.activeRowKey
                          })
                          this.$emit('drawBuildings', this.map, build);
                      }
                  }
              };
          }
        };
        try {
            this.table.dataSource = await baseLayerAPI.listBuildings({
                buildingName: this.building.name,
                landType: this.building.landUseTypes,
                buildingType: this.building.buildingTypes
            });
        } finally {
            this.table.loading = false;
        }

        // 展现建筑边界，根据建筑类型（学校、重点住宅小区、商业中心、医院）以不同颜色进行展
        this.$emit('drawBuildings', this.map, this.table.dataSource);

        // 击“建筑信息表格”中对应建筑名称时，以特定的亮化颜色方式展现对应的建筑边界，
        // 并以图标的方式与建筑相关联的道路（路段）
    }
    async handleEquipment() {
        if (!this.equipment.type) {
            return this.$message.error('无效的条件');
        }
        return this.equipment.type === '卡口' ? this.handlePassport() : this.handleTrafficSignal();
        // 地图上点击公交站点图标，显示公交站点名称；
        // 地图上点击公交线路，展现公交线路名称

        // 点击“设备信息表格”中对应建筑名称时，以特定的亮化颜色方式展现对应的特征信息，
        // 若点击的是卡口地点，将展现对应的卡口，以及展现卡口能监控到的对应路段；
        // 若点击的红绿灯地点，将展现对应的红绿灯，以及红绿灯控制交通的对应路口路段，
        // 若是十字路口，将控制4个路段，若是丁字路口，则展现的3个路段
    }
    async handlePassport() {
        this.activeRowKey = null;
        this.table = {
            rowKey: 'deviceId',
            columns: generateTableColumns(passportColumns),
            loading: true,
            dataSource: [],
            customRow: (row: any) => {
                return {
                    class: 'tr' + (this.activeRowKey === row.deviceId ? ' tr--active' : ''),
                    on: {
                        click: async () => {
                            this.activeRowKey = row.deviceId;
                            this.$emit('drawPassports', this.map, row);
                        }
                    }
                };
            }
        };
        try {
            this.table.dataSource = await baseLayerAPI.listPassports({
                deviceName: this.equipment.name
            });
        } finally {
            this.table.loading = false;
        }

        this.$emit('drawPassports', this.map, this.table.dataSource);
    }
    async handleTrafficSignal() {
        this.activeRowKey = null;
        this.table = {
            rowKey: 'deviceId',
            columns: generateTableColumns(trafficSignalColumns),
            loading: true,
            dataSource: [],
            customRow: (row: any) => {
                return {
                    class: 'tr' + (this.activeRowKey === row.deviceId ? ' tr--active' : ''),
                    on: {
                        click: async() => {
                            this.activeRowKey = row.deviceId;
                            this.$emit('drawTrafficSignals', this.map, row);
                        }
                    }
                };
            }
        };
        try {
            this.table.dataSource = await baseLayerAPI.listTrafficSignals({
                deviceName: this.equipment.name
            });
        } finally {
            this.table.loading = false;
        }

        this.$emit('drawTrafficSignals', this.map, this.table.dataSource);
    }
    async handleMassTransit() {
        if (!this.massTransit.type) {
            return this.$message.error('无效的条件');
        }
        return this.massTransit.type === '公交线路' ? this.handleBusRoute() : this.handleBusStation();

        // 地图上点击公交站点图标，显示公交站点名称；
        // 地图上点击公交线路，展现公交线路名称

        // 点击“交通设施信息表格”中对应公共交通设施名称时，以特定的亮化颜色方式展现对应的特征信息，
        // 若点击的是公交线路，将展现以道路线路进行界面展现，以及以图标展现公交线路中对应的所有公交站点；
        // 若点击的公交站点，将以图标方式展现对应的公交站点，同时展现以此公交站点所属的所有公交线路，以道路线路进行界面展现。
        // 同时，地图上点击公交站点图标，显示公交站点名称；地图上点击公交线路，展现公交线路名称
    }
    async handleBusRoute() {
        // 点击表格，以特定的亮化颜色方式展现对应的特征信息, 同时以图标展现公交线路中对应的所有公交站点；
        this.activeRowKey = null;
        this.table = {
            rowKey: 'directLineId',
            columns: generateTableColumns(busRouteColumns),
            loading: true,
            dataSource: [],
            customRow: (row: any) => {
                return {
                    class: 'tr' + (this.activeRowKey === row.directLineId ? ' tr--active' : ''),
                    on: {
                        click: () => {
                            this.activeRowKey = row.directLineId;
                            this.$emit('drawBusRoutes', this.map, row);
                        }
                    }
                };
            }
        };
        try {
            const data = await baseLayerAPI.listBusRoutes({
                deviceName: this.massTransit.name
            });
            data.forEach((_: any) => {
                _.isMainDirect = _.isMainDirect === 1 ? '是' : '否';
                _.isSection = _.isSection === 1 ? '是' : '否';
                _.startLineTime = `${_.startLineTime.slice(0, 2)}:${_.startLineTime.slice(2)}`
                _.endLineTime = `${_.endLineTime.slice(0, 2)}:${_.endLineTime.slice(2)}`
            });
            this.table.dataSource = data;
        } finally {
            this.table.loading = false;
        }

        // 地图上点击公交线路，展现公交线路名称
        this.$emit('drawBusRoutes', this.map, this.table.dataSource);
    }
    async handleBusStation() {
        // 点击表格，以特定的亮化颜色方式展现对应的特征信息,
        // 同时展现以此公交站点所属的所有公交线路，以道路线路进行界面展现。
        this.activeRowKey = null;
        this.table = {
            rowKey: 'siteId',
            columns: generateTableColumns(busStationColumns),
            loading: true,
            dataSource: [],
            customRow: (row: any) => {
                return {
                    class: 'tr' + (this.activeRowKey === row.siteId ? ' tr--active' : ''),
                    on: {
                        click: async() => {
                            this.activeRowKey = row.siteId;
                            let stop = await baseLayerAPI.listBusStationRoutes({
                                // @ts-ignore
                                stopId: this.activeRowKey
                            })
                            this.$emit('drawBusStations', this.map, stop);
                        }
                    }
                };
            }
        };
        try {
            this.table.dataSource = await baseLayerAPI.listBusStations({
                deviceName: this.massTransit.name
            });
        } finally {
            this.table.loading = false;
        }

        // 地图上点击公交站点图标，显示公交站点名称；
        this.$emit('drawBusStations', this.map, this.table.dataSource);
    }
    async apply() {
        switch (this.selectedDimension) {
            case 'road':
                return this.handleRoad();
            case 'building':
                return this.handleBuilding();
            case 'equipment':
                return this.handleEquipment();
            case 'massTransit':
                return this.handleMassTransit();
            default:
                return this.$message.error('无效的条件');
        }
    }
}

function generateTableColumns(columnSources: ColumnSource[]) {
    return columnSources.map(item => ({
        title: item[0],
        dataIndex: item[1],
        ...item[2]
    }));
}
</script>

<style lang="scss" scoped>
.section {
    margin-bottom: 20px;
}
.map {
    height: 600px;
}
.form,
.form__title,
.form__item {
    display: flex;
}
.form {
    margin-bottom: 10px;
    border: 1px solid #e5e7e9;
}
.form__title {
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e5e7e9;
    width: 7em;
    font-weight: bold;
}
.form__item {
    padding: 10px;
}
.form__item__label {
    flex-shrink: 0;
    margin-right: 0.5em;
    width: 5.5em;
    text-align: right;
}

/deep/ {
    .tr {
        cursor: pointer;
    }
    .tr--active > td {
        background: #afcdf7 !important;
    }
}
</style>
